package com.example.elmmerchants.Create_Shop;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import java.io.ByteArrayOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Shop_Information_Page extends AppCompatActivity {

    String user_email, first_category, second_category, shop_status, qualification_status, legal_status;
    String shop_type = "普通门店";
    byte[] image_string = new byte[0];

    RadioGroup set_shop_type;
    RelativeLayout set_category;
    TextView first_category_text_view, second_category_text_view, shop_information_status, qualification_information_status, legal_information_status;
    EditText contact_name, contact_phone_number, shop_name;
    ImageView shop_avatar;
    Button next_step, jump;
    Uri image1;
    boolean is_upload_image = false;
    boolean is_loading_qualification_page = false, is_upload_data = false;
    String location, licence_status, food_licence_status;
    AlertDialog dialog;

    private final ActivityResultLauncher<Intent> shop_avatar_activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult o) {
            if (o.getResultCode() == RESULT_OK) {
                if (o.getData() != null) {
                    image1 = o.getData().getData();
                    Glide.with(getApplicationContext()).load(image1).into(shop_avatar);

                    try {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), image1);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        image_string = baos.toByteArray();
                        is_upload_image = true;

                    } catch (Exception e) {
                    }
                }
            }
            else {
                Toast.makeText(Shop_Information_Page.this, "请选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    });

    private class Loading_Qualification_Data_Thread extends Thread {
        @Override
        public void run() {
            is_loading_qualification_page = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL connectionSql = new Connection_SQL();
                    Connection connection = connectionSql.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, user_email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        if (set.getString("shop_place").isEmpty()) {
                            location = "暂无";
                        } else {
                            location = set.getString("shop_place");
                        }

                        if (set.getBlob("licence_picture") == null) {
                            licence_status = "去上传";
                        } else {
                            licence_status = "已上传";
                        }

                        if (set.getBlob("food_business_licence_picture") == null) {
                            food_licence_status = "去上传";
                        } else {
                            food_licence_status = "已上传";
                        }
                    }
                    is_loading_qualification_page = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_qualification_page) {
                try {
                    Thread.sleep( 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Shop_Information_Page.this, Qualification_Information_Page.class);
                    intent.putExtra("user_email", user_email);
                    intent.putExtra("shop_information_status", shop_status);
                    intent.putExtra("qualification_information_status", qualification_status);
                    intent.putExtra("legal_information_status", legal_status);
                    intent.putExtra("location", location);
                    intent.putExtra("licence_status", licence_status);
                    intent.putExtra("food_licence_status", food_licence_status);
                    startActivity(intent);
                    finish();
                }
            });
        }
    }

    private class Upload_Data_Thread extends Thread {
        @Override
        public void run() {
            is_upload_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL connectionSql = new Connection_SQL();
                    Connection connection = connectionSql.connection();
                    Blob blobUpload = connection.createBlob();
                    blobUpload.setBytes(1, image_string);
                    String sql = "update `merchant` set contact = ?, contact_phone_number = ?, shop_name = ?, shop_type = ?, shop_picture = ?, shop_information = ?, first_category = ?, second_category = ? where email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, contact_name.getText().toString());
                    preparedStatement.setString(2, contact_phone_number.getText().toString());
                    preparedStatement.setString(3, shop_name.getText().toString());
                    preparedStatement.setString(4, shop_type);
                    preparedStatement.setBlob(5, blobUpload);
                    preparedStatement.setInt(6, 1);
                    preparedStatement.setString(7, first_category);
                    preparedStatement.setString(8, second_category);
                    preparedStatement.setString(9, user_email);
                    preparedStatement.executeUpdate();
                    is_upload_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                while (!is_upload_data) {
                    try {
                        Thread.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(Shop_Information_Page.this, Set_Shop_Data.class);
                        setResult(1, intent);
                        finish();
                    }
                });
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_information_page);

        user_email = getIntent().getStringExtra("user_email");
        first_category = getIntent().getStringExtra("first_category");
        second_category = getIntent().getStringExtra("second_category");
        shop_status = getIntent().getStringExtra("shop_information_status");
        qualification_status = getIntent().getStringExtra("qualification_information_status");
        legal_status = getIntent().getStringExtra("legal_information_status");

        first_category_text_view = findViewById(R.id.first_category);
        second_category_text_view = findViewById(R.id.second_category);
        contact_name = findViewById(R.id.contact_name);
        contact_phone_number = findViewById(R.id.contact_phone_number);
        shop_name = findViewById(R.id.shop_name);
        shop_avatar = findViewById(R.id.shop_avatar);
        next_step = findViewById(R.id.next_step);
        shop_information_status = findViewById(R.id.shop_information_status);
        qualification_information_status = findViewById(R.id.qualification_information_status);
        legal_information_status = findViewById(R.id.legal_information_status);
        jump = findViewById(R.id.jump);

        if (shop_status.equals("已录入")) {
            shop_information_status.setText("已完成");
        }

        if (qualification_status.equals("已录入")) {
            qualification_information_status.setText("已完成");
        }

        if (legal_status.equals("已录入")) {
            legal_information_status.setText("已完成");
        }

        first_category_text_view.setText(first_category);
        second_category_text_view.setText(second_category);
        
        jump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (qualification_status.equals("已录入") && legal_status.equals("已录入")) {
                    Toast.makeText(Shop_Information_Page.this, "目前只余下当前页面未完成", Toast.LENGTH_SHORT).show();
                }
                else if (qualification_status.equals("已录入")) {
                    Intent intent = new Intent(Shop_Information_Page.this, Legal_Information_Page.class);
                    intent.putExtra("user_email", user_email);
                    intent.putExtra("shop_information_status", shop_status);
                    intent.putExtra("qualification_information_status", qualification_status);
                    intent.putExtra("legal_information_status", legal_status);
                    startActivity(intent);
                    finish();
                }
                else {
                    set_dialog();
                    Loading_Qualification_Data_Thread loadingQualificationDataThread = new Loading_Qualification_Data_Thread();
                    loadingQualificationDataThread.start();
                }
            }
        });

        shop_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                shop_avatar_activityResultLauncher.launch(intent);
            }
        });

        next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!is_upload_image || contact_name.getText().toString().isEmpty() || contact_phone_number.getText().toString().isEmpty() || shop_name.getText().toString().isEmpty()) {
                    Toast.makeText(Shop_Information_Page.this, "请输入所有数据", Toast.LENGTH_SHORT).show();
                }
                else {
                    set_dialog();

                    Upload_Data_Thread uploadDataThread = new Upload_Data_Thread();
                    uploadDataThread.start();
                }
            }
        });

        set_category = findViewById(R.id.set_category);
        set_category.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Shop_Information_Page.this, Create_Shop_Page.class);
                intent.putExtra("user_email", user_email);
                startActivityForResult(intent, 3);
            }
        });

        set_shop_type = findViewById(R.id.set_shop_type);
        set_shop_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton type = findViewById(radioGroup.getCheckedRadioButtonId());
                shop_type = type.getText().toString();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 3: {
                first_category = data.getStringExtra("first_category");
                second_category = data.getStringExtra("second_category");
                first_category_text_view.setText(first_category);
                second_category_text_view.setText(second_category);
                break;
            }
        }
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }
}